<template>
  <div>
    <h3>搜索列表</h3>
    <input type="text" placeholder="请输入要搜索的姓名" v-model="searchName" />
    <ul>
      <li v-for="(p, index) in filterPersons" :key="perspnsKey[index]">
        {{ index + 1 }} 姓名： {{ p.name }}---性别：{{ p.sex }} -----年龄：{{
          p.age
        }}-----电话：{{ p.phone }}
      </li>
    </ul>

    <h3>排序</h3>
    <button @click="orderByAge(0)">默认</button>
    <button @click="orderByAge(2)">年龄↑</button>
    <button @click="orderByAge(1)">年龄↓</button>
  </div>
</template>

<script>
import shortId from 'shortid'
export default {
  data() {
    return {
      searchName: '',
      perspns: [
        { name: '张三', sex: '女', age: 19, phone: '1891212121' },
        { name: '李四', sex: '女', age: 22, phone: '1891212121' },
        { name: '王五', sex: '女', age: 29, phone: '1891212121' },
        { name: '赵六', sex: '女', age: 19, phone: '1891212121' },
        { name: '钱七', sex: '女', age: 32, phone: '1891212121' },
        { name: '王二', sex: '女', age: 19, phone: '1891212121' },
        { name: '李四', sex: '女', age: 31, phone: '1891212121' },
        { name: '张三', sex: '女', age: 19, phone: '1891212121' },
        { name: '赵六', sex: '女', age: 34, phone: '1891212121' },
        { name: '王五', sex: '女', age: 26, phone: '1891212121' },
        { name: '王五', sex: '女', age: 28, phone: '1891212121' },
        { name: '张三', sex: '女', age: 19, phone: '1891212121' }
      ],
      perspnsKey: [],
      orderType: 0 // 排序
    }
  },
  mounted() {
    this.perspnsKey = this.perspns.map(v => shortId.generate())
  },
  computed: {
    filterPersons() {
      // 1。获取数据
      var { searchName, perspns, orderType } = this
      // 2.取数组中的数据
      let arr = [...perspns]
      // 3.过滤数组
      if (searchName.trim()) {
        // 如果没有值
        arr = perspns.filter(p => p.name.indexOf(searchName) !== -1)
      }
      // 4.排序
      if (orderType) {
        arr.sort((p1, p2) => {
          if (orderType === 1) {
            // 降序
            return p2.age - p1.age
          } else {
            // 升序
            return p1.age - p2.age
          }
        })
      }
      return arr
    },
    orderByAge(orderType) {
      this.orderType = orderType
    }
  }
}
</script>
